package schedule

import (
	"encoding/json"
	"errors"
	"log/slog"
	"raymond/api/tron"
	"raymond/global"
	"raymond/model"
	"raymond/util"
	"strings"
	"time"
)

func ListenTest() {
	//tron.ListenTRC20("TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj", "TEr89ptiujjR93h5wfvmMRNQbwnzYL6wp2")
	tron.ListenTRC20("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf", "TWPP6GcZfyavuYQVmrq2todir5aiASGUaL")
}
func ListenTRC20Recharge() {
	contractList := tron.GetTrc20ContractList()

	tronContractWallets := model.ListContractWallet(global.TRC)
	if tronContractWallets == nil || len(*tronContractWallets) == 0 || contractList == nil || len(contractList) == 0 {
		return
	}
	cwMap := make(map[string][]model.BSNContractWallet)
	var addrs []string
	for _, tcw := range *tronContractWallets {
		cwMap[tcw.Contract] = append(cwMap[tcw.Contract], tcw)
		addrs = append(addrs, tcw.Addr)
	}

	for _, contract := range contractList {
		var tronTxList []model.TronTransactionJournal
		for _, wallet := range cwMap[contract] {
			resp, err := tron.ListenTRC20(contract, wallet.Addr)
			if err != nil {
				slog.Error("listen TRON TRC20 error:", err)
				continue
			}
			if len(resp.Result) <= 0 {
				continue
			}
			txList := model.AllTronTxList()
			hashList := make([]string, len(*txList))
			for i, tx := range *txList {
				hashList[i] = tx.Hash
			}

			for _, tx := range resp.Result {
				if util.InStrings(tx.Hash, &hashList) {
					continue
				}
				if strings.EqualFold(tx.From, tx.To) {
					continue
				}
				if !util.InStrings(tx.To, &addrs) {
					continue
				}
				dbTronTx := &model.TronTransactionJournal{
					BlockNumber:     tx.BlockNumber,
					TimeStamp:       tx.TimeStamp,
					Hash:            tx.Hash,
					BlockHash:       tx.BlockHash,
					FromAddr:        tx.From,
					ContractAddress: tx.ContractAddress,
					ToAddr:          tx.To,
					Value:           tx.Value,
					InputData:       tx.InputData,
					Confirmations:   tx.Confirmations,
				}
				err := rechargeTRC20(tx.From, tx.To, tx.Value)
				if err != nil {
					slog.Error("recharge err", err)
					continue
				}
				tronTxList = append(tronTxList, *dbTronTx)
			}
		}
		exists := make(map[string]bool)
		journalSet := make([]model.TronTransactionJournal, 0)
		for _, tx := range tronTxList {
			lowerHash := strings.ToLower(tx.Hash)
			if _, ok := exists[lowerHash]; !ok {
				exists[lowerHash] = true
				journalSet = append(journalSet, tx)
			}
		}
		if len(journalSet) > 0 {
			err := model.BatchInsertTronTxJournal(&journalSet)
			if err != nil {
				slog.Error("save txJournal err", err)
			}
		}
	}
}

func rechargeTRC20(from string, to string, value string) error {
	now := time.Now().Unix()
	req := recharge_request{
		CryptoCurrency: string(global.BCPCTRC20),
		Amount:         value,
		From:           from,
		To:             to,
		OrderTime:      now,
	}
	req_bytes, _ := json.Marshal(req)
	url := global.GetAppAddr() + "/order/recharge"
	resp_bytes, err := global.HttpPost(url, req_bytes)
	if err != nil {
		return err
	}
	var resp recharge_response
	json.Unmarshal(resp_bytes, &resp)
	if resp.Code != 200 {
		return errors.New(resp.DetailMessage)
	}
	return nil
}
